package com.ds.robot.assistant.common;

public class NumberUtil {

    private static final String[] NUMBERS = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
    private static final String[] UNITS = {"", "十", "百", "千"};

    public static String numberToChinese(int number) {
        if (number < 0 || number > 9999) {
            return "数字超出范围";
        }

        StringBuilder result = new StringBuilder();
        boolean zeroFlag = false; // 用于标记是否应该忽略连续的零

        for (int i = 0; number > 0; i++) {
            int unitValue = number % 10; // 获取当前位的数值
            if (unitValue == 0) {
                if (!zeroFlag && i != 0) { // 不是第一个零且不是连续零时添加"零"
                    result.insert(0, NUMBERS[unitValue]);
                    zeroFlag = true;
                }
            } else {
                result.insert(0, UNITS[i]).insert(0, NUMBERS[unitValue]);
                zeroFlag = false; // 重置零标记
            }
            number /= 10; // 处理下一位
        }

        // 处理结果中开头的"零"或"一十"等特殊情况
        if (result.length() > 0 && result.charAt(0) == '零') {
            result.deleteCharAt(0);
        }
        if (result.length() > 1 && result.charAt(0) == '一' && result.charAt(1) == '十') {
            result.deleteCharAt(0);
        }

        return result.length() == 0 ? "零" : result.toString();
    }

    public static void main(String[] args) {
        System.out.println(numberToChinese(0));       // 输出：零
        System.out.println(numberToChinese(1));       // 输出：零
        System.out.println(numberToChinese(3));       // 输出：零
        System.out.println(numberToChinese(101));     // 输出：一百零一
        System.out.println(numberToChinese(1001));    // 输出：一千零一
        System.out.println(numberToChinese(1234));    // 输出：一千二百三十四
        System.out.println(numberToChinese(9999));    // 输出：九千九百九十九
        System.out.println(numberToChinese(10000));   // 输出：数字超出范围
    }
}
